/**
 * @fileOverview
 * @author rekey
 * Created by rekey on 10/5/14.
 */
var fs = require('fs');
var jade = require('jade');
/*
 * jade的配置项可以自己配置一个编译器。
 * 这个函数就是自定义的编译器，先把parse出来的blocks取出来，然后写一个配置替换掉layout里的占位
 * */
function compiler(tokens, locals) {
  //layout里第二行是一个block，可以拿到当前的全部block
  var blocks = tokens.nodes[1].parser.blocks;
  var hasBlock = {};
  //循环blocks，检测block的情况
  Object.keys(blocks).forEach(function (key) {
    //console.log('----', key, '----');
    var item = blocks[key];
    var blockHasNodes = item.nodes.length > 1 || item.nodes[0].str != '' || item.nodes[0].name;
    //写入配置
    hasBlock[key] = blockHasNodes || item.appended.length > 0 || item.prepended.length > 0;
  });
  //删除自定义的编译器
  delete locals.compiler;
  //重新解释模板，拿到编译结果
  var parser = new jade.Parser(fs.readFileSync(locals.filename, 'utf-8'), locals.filename, locals);
  var _tokens;
  try {
    // Parse
    _tokens = parser.parse();
  } catch (err) {
    parser = parser.context();
    jade.runtime.rethrow(err, parser.filename, parser.lexer.lineno, parser.input);
  }
  //console.log(_tokens.nodes[2]);
  //替换占位符为一个javascript配置
  _tokens.nodes[2].val = 'var hasBlock = ' + JSON.stringify(hasBlock) + ';';
  _tokens.nodes[2].buffer = false;
  _tokens.nodes[2].escape = false;
  //console.log(_tokens.nodes[2]);
  //返回默认编译器的编译结果
  return new jade.Compiler(_tokens, locals);
}
module.exports = function (app) {
  app.engine('jade', jade.renderFile);
  app.set('views', global.appPath + '/views');
  app.set('view engine', 'jade');
  var isDevelopment = 'development' == app.get('env');
  var options = {
    compileDebug: false,
    cache: true,
    pretty: true
  };
  if (isDevelopment) {
    options = {
      compileDebug: true,
      pretty: true
    };
    delete options.cache;
  }
  console.log(options);
  return function (req, res, next) {
    res.locals.pretty = options.pretty;
    res.locals.compileDebug = options.compileDebug;
    res.locals.cache = options.cache;
    res.locals.compiler = compiler;
    next();
  };
};